package servlets;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.codec.digest.DigestUtils;

import pojo.User;
import tools.Tool;
import utils.db.impl.UserFetcher;

/**
 * Servlet implementation class LoginServlet
 */
@WebServlet("/LoginServlet")
public class LoginServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String email=request.getParameter("email");
		String password = DigestUtils.md5Hex(request.getParameter("password"));
		HttpSession session;
	
		if(email!="" && password!=""){
			if(Tool.checkEmailFormat(email)){
				UserFetcher u = new UserFetcher();
				User user = u.getUser(email, password);
				System.out.println(u.getUser(email, password));
				if(user!=null && user.getId()!=null){
					session = request.getSession(true);
					session.setAttribute("user", new User(user.getId(), user.getFirstName(),user.getLastName(),user.getPassword(),user.getEmail(),user.getType(),user.getPhoneNumber()));
					response.setStatus(HttpServletResponse.SC_MOVED_TEMPORARILY);
					response.setHeader("Location", "index.jsp");
				}else{
					session = request.getSession(true);
					session.setAttribute("warning", "Błedny login lub hasło!");
					response.setStatus(HttpServletResponse.SC_MOVED_TEMPORARILY);
					response.setHeader("Location", "index.jsp?page=login#page");
				}
			}else{
				session = request.getSession(true);
				session.setAttribute("warning", "Błedny format email!");
			    response.setStatus(HttpServletResponse.SC_MOVED_TEMPORARILY);
			    response.setHeader("Location", "index.jsp?page=login#page");
			}
		}
	}

}
